package controllers

import (
	"B2Cshop/models"

	"github.com/astaxie/beego"
)

type UserControllers struct {
	beego.Controller
}

func (c *UserControllers) Get() {
	c.TplName = "user_list.html"
}

//用户注册
func (c *UserControllers) UserRegister() {
	phone, _ := c.GetInt64("phone")
	password := c.GetString("password")
	againPassword := c.GetString("againPassword")

	//判断两次输入密码是否相同
	if password != againPassword {
		c.Data["json"] = models.JsonBody{Code: models.CODE1002, Message: models.MSG1002}

	} else {

		//判断该手机号是否已被注册
		checkCode, checkMsg := models.CheckUserPhone(phone)
		if checkCode == models.CODE1003 {
			c.Data["json"] = models.JsonBody{Code: checkCode, Message: checkMsg}
		} else {
			code, msg, id := models.UserRegisterByPhone(phone, password)
			c.Data["json"] = models.JsonBody{Code: code, Message: msg}
			c.SetSession("uid", id)
		}
	}
	c.ServeJSON()
}

//用户登录
func (c *UserControllers) Login() {
	phone, _ := c.GetInt64("phone")
	password := c.GetString("password")

	//检测用户和密码是否正确
	checkCode, checkMsg := models.CheckUserLogin(phone, password)
	c.Data["json"] = models.JsonBody{Code: checkCode, Message: checkMsg}

	if checkCode == models.CODE1004 {
		c.Data["json"] = models.JsonBody{Code: checkCode, Message: checkMsg}
	} else {
		code, msg, arr, uId := models.GetUserDataByPhone(phone)
		c.Data["json"] = models.JsonBody{Code: code, Message: msg, Data: arr}
		c.SetSession("uid", uId)
	}
	c.ServeJSON()
}

//获取个人中心首页
func (c *UserControllers) UserCenter() {
	id := c.GetSession("uid")
	code, msg, data := models.GetUserCenterById(id)
	c.Data["json"] = models.JsonBody{Code: code, Message: msg, Data: data}
	c.ServeJSON()
}

//修改个人昵称
func (c *UserControllers) SetUserNickname() {
	nickname := c.GetString("nickname")
	id := c.GetSession("uid")
	code, msg := models.UpdateUserNicknameById(id, nickname)
	c.Data["json"] = models.JsonBody{Code: code, Message: msg}
	c.ServeJSON()
}

//修改用户密码
func (c *UserControllers) SetUserPassword() {
	oldPassword := c.GetString("oldPassword")
	newPassword := c.GetString("newPassword")
	againPassword := c.GetString("againPassword")
	id := c.GetSession("uid")

	//检查旧密码是否存在
	checkPasswordCode, checkPasswordMsg := models.CheckUserPasswordById(id, oldPassword)
	if checkPasswordCode == models.CODE1004 {
		c.Data["json"] = models.JsonBody{Code: checkPasswordCode, Message: checkPasswordMsg}
	} else {
		//检查2次密码输入是否相同
		if newPassword != againPassword {
			c.Data["json"] = models.JsonBody{Code: models.CODE1002, Message: models.MSG1002}
		} else {
			code, msg := models.UpdateUserPasswordById(id, newPassword)
			c.Data["json"] = models.JsonBody{Code: code, Message: msg}
		}
	}

	c.ServeJSON()
}
